package com.huiqiao.lesson4.utils;

import com.huiqiao.lesson4.mapper.*;
import lombok.Getter;
import lombok.extern.log4j.Log4j2;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

@Log4j2
public class DBUtils {

    private static SqlSessionFactory sqlSessionFactory;
    private static SqlSession session;

    @Getter
    private static SysUserMapper userMapper;
    @Getter
    private static SysMenuMapper menuMapper;
    @Getter
    private static SysRoleMapper roleMapper;
    @Getter
    private static SysRoleMenuMapper roleMenuMapper;
    @Getter
    private static SysUserRoleMapper userRoleMapper;

    // 静态代码块只执行一次
    static {
        log.info("触发 static方法");
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            log.info("SqlSessionFactory 初始化成功");

            session = sqlSessionFactory.openSession(true);
            log.info("SqlSession 初始化成功");

            userMapper = session.getMapper(SysUserMapper.class);
            log.info("SysUserMapper 初始化成功");

            menuMapper = session.getMapper(SysMenuMapper.class);
            log.info("SysMenuMapper 初始化成功");

            roleMapper = session.getMapper(SysRoleMapper.class);
            log.info("SysRoleMapper 初始化成功");

            roleMenuMapper = session.getMapper(SysRoleMenuMapper.class);
            log.info("SysRoleMenuMapper 初始化成功");

            userRoleMapper = session.getMapper(SysUserRoleMapper.class);
            log.info("SysUserRoleMapper 初始化成功");

        } catch (IOException e) {
            log.error("初始化 SqlSessionFactory 失败", e);
            throw new ExceptionInInitializerError(e);
        }
    }

    public static void close() {
        if (session != null) {
            session.close();
            log.info("关闭SqlSession");
        }
    }
}
